/**
 * XappTool UniApp SDK
 * 免邀请安装归因 SDK
 * 类似 xinstall/openinstall/sharetrace 功能
 * @version 1.0.0
 */

// #ifdef H5
// H5平台使用Web SDK（通过全局对象）
const XappToolWeb = (typeof window !== 'undefined' && window.XappTool) ? window.XappTool : null;
// #endif

// #ifndef H5
// 非H5平台使用原生实现
const XappToolUniApp = (function() {
  'use strict';

  /**
   * 工具函数
   */
  const Utils = {
    // 生成唯一ID
    generateUUID() {
      return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        const r = Math.random() * 16 | 0;
        const v = c === 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
      });
    },

    // 获取设备信息
    getDeviceInfo() {
      const systemInfo = uni.getSystemInfoSync();
      return {
        brand: systemInfo.brand,
        model: systemInfo.model,
        system: systemInfo.system,
        platform: systemInfo.platform,
        version: systemInfo.version,
        screenWidth: systemInfo.screenWidth,
        screenHeight: systemInfo.screenHeight,
        windowWidth: systemInfo.windowWidth,
        windowHeight: systemInfo.windowHeight,
        pixelRatio: systemInfo.pixelRatio,
        language: systemInfo.language,
        fontSizeSetting: systemInfo.fontSizeSetting,
        SDKVersion: systemInfo.SDKVersion,
        statusBarHeight: systemInfo.statusBarHeight,
        safeArea: systemInfo.safeArea,
        deviceId: systemInfo.deviceId || this.generateUUID(),
        uuid: this.generateUUID()
      };
    },

    // 生成设备指纹
    generateDeviceFingerprint() {
      const deviceInfo = this.getDeviceInfo();
      const fingerprintString = JSON.stringify({
        brand: deviceInfo.brand,
        model: deviceInfo.model,
        system: deviceInfo.system,
        platform: deviceInfo.platform,
        screenWidth: deviceInfo.screenWidth,
        screenHeight: deviceInfo.screenHeight,
        language: deviceInfo.language,
        pixelRatio: deviceInfo.pixelRatio,
        deviceId: deviceInfo.deviceId
      });
      return this.sha256(fingerprintString);
    },

    // 哈希函数
    hashCode(str) {
      let hash = 0;
      if (str.length === 0) return hash;
      for (let i = 0; i < str.length; i++) {
        const char = str.charCodeAt(i);
        hash = ((hash << 5) - hash) + char;
        hash = hash & hash;
      }
      return Math.abs(hash).toString(36);
    },

    // 防抖函数
    debounce(func, wait) {
      let timeout;
      return function executedFunction(...args) {
        const later = () => {
          clearTimeout(timeout);
          func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
      };
    },

    // 节流函数
    throttle(func, limit) {
      let inThrottle;
      return function() {
        const args = arguments;
        const context = this;
        if (!inThrottle) {
          func.apply(context, args);
          inThrottle = true;
          setTimeout(() => inThrottle = false, limit);
        }
      };
    },

    // 深度克隆
    deepClone(obj) {
      if (obj === null || typeof obj !== 'object') return obj;
      if (obj instanceof Date) return new Date(obj.getTime());
      if (obj instanceof Array) return obj.map(item => this.deepClone(item));
      if (typeof obj === 'object') {
        const cloned = {};
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            cloned[key] = this.deepClone(obj[key]);
          }
        }
        return cloned;
      }
    },

    // 压缩数据
    compress(data) {
      try {
        return encodeURIComponent(JSON.stringify(data));
      } catch (e) {
        return data;
      }
    },

    // 解压缩数据
    decompress(data) {
      try {
        return JSON.parse(decodeURIComponent(data));
      } catch (e) {
        return data;
      }
    },

    // 获取网络类型
    getNetworkType() {
      return new Promise((resolve) => {
        uni.getNetworkType({
          success: (res) => {
            resolve(res.networkType);
          },
          fail: () => {
            resolve('unknown');
          }
        });
      });
    },

    // 获取存储信息
    getStorageInfo() {
      return new Promise((resolve) => {
        uni.getStorageInfo({
          success: (res) => {
            resolve(res);
          },
          fail: () => {
            resolve({});
          }
        });
      });
    },

    // 检测模拟器
    detectEmulator() {
      const deviceInfo = this.getDeviceInfo();
      const emulatorKeywords = [
        'bluestacks', 'nox', 'memu', 'koplayer', 'droid4x',
        'andy', 'genymotion', 'windroy', 'youwave', 'leapdroid',
        'emulator', 'simulator', 'virtual'
      ];
      
      const deviceString = `${deviceInfo.brand} ${deviceInfo.model} ${deviceInfo.system}`.toLowerCase();
      return emulatorKeywords.some(keyword => deviceString.includes(keyword));
    },

    // 检测异常设备
    detectAnomalousDevice() {
      const deviceInfo = this.getDeviceInfo();
      const anomalies = [];
      
      // 检查屏幕尺寸异常
      if (deviceInfo.screenWidth <= 0 || deviceInfo.screenHeight <= 0) {
        anomalies.push('Invalid screen dimensions');
      }
      
      // 检查设备信息缺失
      if (!deviceInfo.brand || !deviceInfo.model || !deviceInfo.system) {
        anomalies.push('Missing device information');
      }
      
      // 检查像素比异常
      if (deviceInfo.pixelRatio <= 0) {
        anomalies.push('Invalid pixel ratio');
      }
      
      return {
        isAnomalous: anomalies.length > 0,
        reasons: anomalies
      };
    }
  };

  /**
   * XappTool UniApp SDK 主类
   */
  class XappTool {
    constructor(options = {}) {
      this.config = {
        apiKey: '',
        apiUrl: 'https://api.xapptool.cn',
        timeout: 5000,
        debug: false,
        environment: 'production',
        device: {
          include: [],
          exclude: [],
          customData: {}
        },
        performance: {
          enableCache: true,
          cacheTimeout: 3600000,
          enableCompression: true,
          batchRequests: false,
          batchSize: 10,
          batchInterval: 5000
        },
        privacy: {
          gdpr: { enabled: false },
          ccpa: { enabled: false }
        },
        ...options
      };
      
      this.isInitialized = false;
      this.deviceFingerprint = '';
      this.sessionId = Utils.generateUUID();
      this.cache = new Map();
      this.requestQueue = [];
      this.eventListeners = {};
      this.deviceInfo = {};
      
      this.initDeviceInfo();
    }

    /**
     * 初始化设备信息
     */
    initDeviceInfo() {
      this.deviceInfo = Utils.getDeviceInfo();
      this.deviceFingerprint = Utils.generateDeviceFingerprint();
    }

    /**
     * 初始化 SDK
     */
    async init(options = {}) {
      try {
        this.config = { ...this.config, ...options };
        
        if (!this.config.apiKey) {
          throw new Error('API Key is required');
        }
        
        this.log('Initializing XappTool UniApp SDK...');
        
        // 更新设备信息
        this.initDeviceInfo();
        
        // 检查隐私合规
        if (this.config.privacy.gdpr.enabled || this.config.privacy.ccpa.enabled) {
          await this.checkPrivacyCompliance();
        }
        
        // 启动性能监控
        if (this.config.performance.enableCache) {
          this.startCacheCleanup();
        }
        
        // 启动批量请求处理
        if (this.config.performance.batchRequests) {
          this.startBatchProcessor();
        }
        
        this.isInitialized = true;
        this.emit('ready', { 
          deviceFingerprint: this.deviceFingerprint,
          deviceInfo: this.deviceInfo
        });
        
        this.log('XappTool UniApp SDK initialized successfully');
        return { 
          success: true, 
          deviceFingerprint: this.deviceFingerprint,
          deviceInfo: this.deviceInfo
        };
        
      } catch (error) {
        this.log('SDK initialization failed:', error);
        this.emit('error', error);
        throw error;
      }
    }

    /**
     * 获取安装参数
     */
    async getInstallParams() {
      if (!this.isInitialized) {
        throw new Error('SDK not initialized');
      }
      
      try {
        // 检查缓存
        const cacheKey = 'install_params_' + this.deviceFingerprint;
        if (this.config.performance.enableCache) {
          const cached = this.getCache(cacheKey);
          if (cached) return cached;
        }
        
        // 获取启动参数
        const launchOptions = this.getLaunchOptions();
        
        // 获取场景值
        const scene = await this.getScene();
        
        // 构建请求数据
        const requestData = {
          apiKey: this.config.apiKey,
          deviceFingerprint: this.deviceFingerprint,
          sessionId: this.sessionId,
          deviceInfo: this.deviceInfo,
          scene: scene,
          launchOptions: launchOptions,
          timestamp: Date.now(),
          networkType: await Utils.getNetworkType(),
          storageInfo: await Utils.getStorageInfo()
        };
        
        // 发送归因请求
        const response = await this.request('/api/v1/attribution', requestData);
        
        const installParams = {
          inviter: response.data.inviter || null,
          channel: response.data.channel || null,
          params: response.data.params || {},
          utm: response.data.utm || {},
          scene: scene,
          attributionType: response.data.attributionType || 'organic',
          method: response.data.attributionType || 'organic',
          confidence: response.data.confidence || 0,
          timestamp: response.data.timestamp || Date.now()
        };
        
        // 缓存结果
        if (this.config.performance.enableCache) {
          this.setCache(cacheKey, installParams, this.config.performance.cacheTimeout);
        }
        
        return installParams;
        
      } catch (error) {
        this.log('Failed to get install params:', error);
        
        // 返回默认参数
        return {
          inviter: null,
          channel: null,
          params: {},
          utm: {},
          scene: await this.getScene(),
          attributionType: 'organic',
          method: 'organic',
          confidence: 0,
          timestamp: Date.now()
        };
      }
    }

    /**
     * 生成邀请链接
     */
    async generateInvitationLink(options = {}) {
      if (!this.isInitialized) {
        throw new Error('SDK not initialized');
      }
      
      try {
        const {
          userId = '',
          code = '',
          channel = 'direct',
          params = {},
          expireDays = 7
        } = options;
        
        const requestData = {
          apiKey: this.config.apiKey,
          userId: userId,
          code: code || Utils.generateUUID().substr(0, 8),
          channel: channel,
          params: params,
          expireDays: expireDays,
          deviceFingerprint: this.deviceFingerprint,
          deviceInfo: this.deviceInfo
        };
        
        const response = await this.request('/api/v1/invitation-link', requestData);
        
        return response.data.invitationLink;
        
      } catch (error) {
        this.log('Failed to generate invitation link:', error);
        
        // 生成默认链接
        const pages = getCurrentPages();
        const currentPage = pages[pages.length - 1];
        const route = currentPage.route || currentPage.__route__;
        
        const params = {
          inviter: options.userId || '',
          code: options.code || Utils.generateUUID().substr(0, 8),
          channel: options.channel || 'direct',
          ...options.params
        };
        
        // 构建小程序码或URL
        if (this.deviceInfo.platform === 'mp-weixin') {
          // 微信小程序
          return this.generateWXACode(params);
        } else {
          // 其他平台
          return this.generateUniversalLink(route, params);
        }
      }
    }

    /**
     * 获取设备指纹
     */
    getDeviceFingerprint() {
      return this.deviceFingerprint;
    }

    /**
     * 获取设备信息
     */
    getDeviceInfo() {
      return {
        ...this.deviceInfo,
        fingerprint: this.deviceFingerprint,
        sessionId: this.sessionId,
        isEmulator: Utils.detectEmulator(),
        isAnomalous: Utils.detectAnomalousDevice()
      };
    }

    /**
     * 反作弊检测
     */
    async checkAntiFraud() {
      const results = {
        isSuspicious: false,
        reasons: [],
        isEmulator: Utils.detectEmulator(),
        isAnomalousDevice: Utils.detectAnomalousDevice(),
        isUsingVPN: false,
        isBot: false,
        isHeadless: false,
        hasFakeUserAgent: false,
        pluginsAnomaly: false,
        webDriverDetected: false,
        suspiciousBehavior: {},
        networkType: await Utils.getNetworkType(),
        deviceInfo: this.deviceInfo
      };
      
      // 综合判断
      if (results.isEmulator) {
        results.isSuspicious = true;
        results.reasons.push('Detected emulator environment');
      }
      
      if (results.isAnomalousDevice.isAnomalous) {
        results.isSuspicious = true;
        results.reasons.push(...results.isAnomalousDevice.reasons);
      }
      
      return results;
    }

    /**
     * 获取场景值
     */
    async getScene() {
      return new Promise((resolve) => {
        // 获取启动参数
        const launchOptions = uni.getLaunchOptionsSync();
        resolve(launchOptions.scene || 0);
      });
    }

    /**
     * 获取启动参数
     */
    getLaunchOptions() {
      try {
        return uni.getLaunchOptionsSync();
      } catch (e) {
        return {};
      }
    }

    /**
     * 生成微信小程序码
     */
    async generateWXACode(params) {
      return new Promise((resolve) => {
        // 这里需要后端配合生成小程序码
        // 暂时返回参数对象
        resolve({
          type: 'wxacode',
          params: params,
          scene: Object.keys(params).map(key => `${key}=${params[key]}`).join('&')
        });
      });
    }

    /**
     * 生成通用链接
     */
    generateUniversalLink(route, params) {
      const queryString = Object.keys(params)
        .map(key => `${key}=${encodeURIComponent(params[key])}`)
        .join('&');
      
      return {
        type: 'universal_link',
        url: `/${route}?${queryString}`,
        params: params
      };
    }

    /**
     * 发送请求
     */
    async request(endpoint, data = {}) {
      return new Promise((resolve, reject) => {
        const url = this.config.apiUrl + endpoint;
        
        // 压缩数据
        let requestData = data;
        if (this.config.performance.enableCompression) {
          requestData = { compressed: Utils.compress(data) };
        }
        
        uni.request({
          url: url,
          method: 'POST',
          header: {
            'Content-Type': 'application/json',
            'X-API-Key': this.config.apiKey,
            'X-Session-ID': this.sessionId,
            'X-Fingerprint': this.deviceFingerprint,
            'X-SDK-Version': '1.0.0',
            'X-Platform': 'uniapp'
    },

    getShareUrl(config = {}, params = {}, type = 'auto') {
      const base = (type === 'custom' || config.is_custom_landing) ? `/lp/custom/${config.id}` : `/lp/${config.id}`
      const qs = Object.keys(params).map(k => `${encodeURIComponent(k)}=${encodeURIComponent(params[k])}`).join('&')
      return qs ? `${base}?${qs}` : base
    },
          data: requestData,
          timeout: this.config.timeout,
          success: (res) => {
            if (res.statusCode === 200 && res.data.code === 0) {
              resolve(res.data);
            } else {
              reject(new Error(res.data.message || 'Request failed'));
            }
          },
          fail: (error) => {
            reject(new Error('Request failed: ' + error.errMsg));
          }
        });
      });
    }

    /**
     * 获取渠道统计
     */
    async getChannelStats(options = {}) {
      try {
        const {
          startDate = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString(),
          endDate = new Date().toISOString(),
          channel = ''
        } = options;
        
        const requestData = {
          apiKey: this.config.apiKey,
          startDate: startDate,
          endDate: endDate,
          channel: channel,
          deviceFingerprint: this.deviceFingerprint,
          deviceInfo: this.deviceInfo
        };
        
        const response = await this.request('/api/v1/channel-stats', requestData);
        
        return response.data;
        
      } catch (error) {
        this.log('Failed to get channel stats:', error);
        return {
          totalInstalls: 0,
          channelStats: [],
          conversionRate: 0
        };
      }
    }

    /**
     * 缓存操作
     */
    getCache(key) {
      try {
        const cached = this.cache.get(key);
        if (cached && cached.expires > Date.now()) {
          return cached.data;
        }
        this.cache.delete(key);
        return null;
      } catch (e) {
        return null;
      }
    }

    setCache(key, data, timeout = 3600000) {
      try {
        this.cache.set(key, {
          data: data,
          expires: Date.now() + timeout
        });
      } catch (e) {
        // 忽略缓存错误
      }
    }

    /**
     * 事件监听
     */
    on(event, callback) {
      if (!this.eventListeners[event]) {
        this.eventListeners[event] = [];
      }
      this.eventListeners[event].push(callback);
    }

    off(event, callback) {
      if (this.eventListeners[event]) {
        this.eventListeners[event] = this.eventListeners[event].filter(cb => cb !== callback);
      }
    }

    emit(event, data) {
      if (this.eventListeners[event]) {
        this.eventListeners[event].forEach(callback => {
          try {
            callback(data);
          } catch (e) {
            this.log('Event callback error:', e);
          }
        });
      }
    }

    /**
     * 日志记录
     */
    log(...args) {
      if (this.config.debug) {
        console.log('[XappTool UniApp]', ...args);
      }
    }

    /**
     * 隐私合规检查
     */
    async checkPrivacyCompliance() {
      // GDPR 合规检查
      if (this.config.privacy.gdpr.enabled) {
        const consent = uni.getStorageSync('xapptool_gdpr_consent');
        if (!consent) {
          throw new Error('GDPR consent required');
        }
      }
      
      // CCPA 合规检查
      if (this.config.privacy.ccpa.enabled) {
        const doNotSell = uni.getStorageSync('xapptool_ccpa_do_not_sell');
        if (doNotSell === 'true') {
          throw new Error('CCPA do not sell preference set');
        }
      }
    }

    /**
     * 缓存清理
     */
    startCacheCleanup() {
      setInterval(() => {
        const now = Date.now();
        for (const [key, value] of this.cache.entries()) {
          if (value.expires <= now) {
            this.cache.delete(key);
          }
        }
      }, 60000);
    }

    /**
     * 批量处理
     */
    startBatchProcessor() {
      setInterval(() => {
        if (this.requestQueue.length > 0) {
          const batch = this.requestQueue.splice(0, this.config.performance.batchSize);
          this.processBatchRequest(batch);
        }
      }, this.config.performance.batchInterval);
    }

    async processBatchRequest(requests) {
      try {
        const response = await this.request('/api/v1/batch', { requests });
        this.log('Batch request processed:', response);
      } catch (error) {
        this.log('Batch request failed:', error);
      }
    }

    /**
     * 版本信息
     */
    getVersion() {
      return '1.0.0';
    }

    /**
     * 调试信息
     */
    getDebugInfo() {
      return {
        version: this.getVersion(),
        isInitialized: this.isInitialized,
        deviceFingerprint: this.deviceFingerprint,
        sessionId: this.sessionId,
        deviceInfo: this.deviceInfo,
        config: this.config,
        cacheSize: this.cache.size,
        queueSize: this.requestQueue.length
      };
    }
  }

  return XappTool;
})();
// #endif

const DefaultExport = (typeof window !== 'undefined' && typeof document !== 'undefined') ? XappToolWeb : XappToolUniApp;
export default DefaultExport;